<template>
	<view class="page">
		<lgd-tab :tabValue="tabValue" :tabIndex="tabIndex"  @getIndex="getIndex"  background="#f1f2f3" textColor="rgb(221, 94, 86)"  underlineColor="#fff" />
		<uni-forms ref="baseForm" class="mb100"  :modelValue="formData">
		<view class="group p30 untoradius">
			<template v-if="tabIndex == 0">
				<view class="inputgb">
					<uni-forms-item label="收货地址"  name="orderAddress">
						<view class="pl20 flex flex-items-center flex-between fit-height">
							<view class="fit-width" @click="getAddressList" >
								<view>{{formData.orderAddress || '请选择收货地址'}}</view>
								<view>{{formData.orderPerson}} {{formData.orderPhone}}</view>
							</view>
							<uni-icons @click="getAddressList"  v-if="!formData.orderAddress" type="bottom" size="16" color="#c0c4cc">
							</uni-icons>
							<uni-icons v-else @click="clearAddress" type="clear" size="16" color="#c0c4cc"></uni-icons>
						</view>
					</uni-forms-item>
				</view>
			</template>
			<template v-else-if="tabIndex == 1">
				<view class="inputgb">
					<uni-forms-item label="商家地址" name="address">
						<view @click="openLocation" class="pl20 pr10 flex flex-items-center flex-between fit-height">
							<view class="fit-width"  >
								<view>{{config.address}}</view>
							</view>
							<uni-icons type="bottom" size="16" color="#c0c4cc"></uni-icons>
						</view>
					</uni-forms-item>
					<uni-forms-item label="自提时间" name="orderPickUpTime">
						<FormDatePicker  v-model="formData.orderPickUpTime" :items="dateList" placeholder="请选择自提时间"></FormDatePicker>
					</uni-forms-item>
					<uni-forms-item label="联系方式" name="orderPhone">
						<uni-easyinput :inputBorder="false"  type="number" :maxlength="11" v-model="formData.orderPhone" placeholder="填写手机号,方便商家联系" />
					</uni-forms-item>
				</view>
			</template>
			<template v-else>
				<view class="inputgb">
					<uni-forms-item label="取货点" name="addressPoint">
						<FormPicker v-model="formData.addressPoint" :items="addressType" item-label="name"
							item-value="name" placeholder="请选择取货点"></FormPicker>
					</uni-forms-item>
					<uni-forms-item label="联系方式" name="orderPhone">
						<uni-easyinput :inputBorder="false"  type="number" :maxlength="11" v-model="formData.orderPhone" placeholder="填写手机号,方便商家联系"/>
					</uni-forms-item>
				</view>
			</template>
		</view>
		<view  class="group p30">
			<view class="f40 blod mb30">共 {{total}} 件商品</view>
			<productItem v-for="(item, i) in dataList" :item="item" :key="i"></productItem>
			<template v-if="goodsList.length > 3">
				<view  class="fit-width flex flex-items-center flex-center" v-if="!showMore" @click="showMore = true">
					<text class="f30">展示更多</text>
					<uni-icons type="down" size="20"></uni-icons>
				</view>
				<view class="fit-width flex flex-items-center flex-center" v-else @click="showMore = false">
					<text class="f30">收起更多</text>
					<uni-icons type="up" size="20"></uni-icons>
				</view>
			</template>
			<view class="vrow flex-between" v-if="tabIndex == 0">
				<text>配送费 </text>
				<text class="f40 blod">¥{{deliveryFee}}</text>
			</view>
			<view class="line"></view>
			<view class="flex flex-items-center flex-end mb50">
				<text class="f30">合计</text>
				<text class="ml10 f40 blod">¥{{allPrice}}</text>
			</view>
			<view class="inputgb">
			<uni-forms-item label="备注">
				<uni-easyinput type="textarea" :inputBorder="false" v-model="formData.remarks" placeholder="(选填)" />
			</uni-forms-item>
			</view>
		</view>
		</uni-forms>
		<view class="footer-btns flex flex-items-center flex-between">
			<view>
				<text class="f30">合计</text>
				<text class="ml10 f40 blod">¥{{allPrice}}</text>
			</view>
			 <view class="bigbtn btn-red" @click="createOrder">去支付</view>
		</view>
	</view>
</template>

<script>
	import productItem from './item.vue'
	import FormPicker from '@/components/form-picker/index.vue'
	import FormDatePicker from '@/components/form-picker/date.vue'
	import Big from 'big.js'
	import {CreateOrder, OrderPay, OrderCancel} from '@/pages/common/api.js'
	import {shopCode} from '@/pages/common/js/http.js'
	import moment from 'moment'
	export default {
		components: {productItem, FormPicker, FormDatePicker},
		data () {
			let days = ['今天', moment().add(1, 'd').format('MM月DD日'),  moment().add(2, 'd').format('MM月DD日')]
			let today = ['立即自提', '30分钟后',  '1小时后']
			let times = []
			let dayh = new Date().getHours()
			for (let i = 0; i < 24; i++) {
				let h = i < 10 ? `0${i}` : i
				times.push(`${h}:00`)
				times.push(`${h}:30`)
				if (i > dayh) {
					today.push(`${h}:00`)
					today.push(`${h}:30`)
				}
			}
			
			return {
				tabIndex: 0,
				showMore: false,
				tabValue: [`外送`, `自提`, `定点取货`],
				rule: [{
					required: true,
					errorMessage: '不能为空'
				}],
				addressType: [],
				dateList: [
					days,
					[today, times, times]
				],
				config: {},
				formData: {
					orderAddress: '',
					orderPerson: '',
					orderPhone: '',
					addressPoint: '',
					orderPickUpTime: '',
					remarks: ''
				},
				deliveryFee: 0,
				totalPrice: 0,
				total: 0,
				goodsList: []
			}
		},
		computed: {
			allPrice () {
				if (this.tabIndex == 0) {
					return new Big(this.totalPrice).plus(new Big(this.deliveryFee))
				}
				return this.totalPrice
			},
			dataList () {
				if (this.showMore) {
					return this.goodsList
				} else {
					return this.goodsList.slice(0, 3)
				}
			}
		},
		onLoad () {
			let payList = uni.getStorageSync('pay-list')
			console.log('payList=====', payList)
			let totalPrice = 0
			let total = 0
			this.goodsList = payList.reduce((a, d) => {
				a.push(...d.list)
				totalPrice = new Big(totalPrice).plus(new Big(d.list.reduce((t, i) => {
					t = new Big(t).plus(new Big(i.price).times(i.selected));
					total += i.selected
					return t
				}, 0)))
				return a
			}, [])
			let config = uni.getStorageSync('config')
			this.addressType = config.placeList.map(d => {
				return {
					name: d
				}
			})
			this.deliveryFee = config.deliveryFee || 0
			this.totalPrice = totalPrice
			this.total = total
			this.config = config
			console.log('config', config)
		},
		methods: {
			openLocation (e) {
				console.log(e)
				uni.openLocation({
				  longitude: Number(this.config.lng),
				  latitude: Number(this.config.lat),
				  name: '商家地址',
				  address: this.config.address
				})
			  },
			clearAddress () {
				this.formData.orderAddress = ''
				this.formData.orderPerson = ''
				this.formData.orderPhone = ''
			},
			 getAddressList() {  
			      uni.chooseAddress({  
			        success: (res) => {  
						console.log('获取地址', res)
						if (res.errMsg == "chooseAddress:ok") {
							this.formData.orderAddress = `${res.cityName}${res.countyName}${res.detailInfo}`;  
							this.formData.orderPerson = `${res.userName}`
							this.formData.orderPhone = `${res.telNumber}`
						}
			        },  
			        fail: (err) => {  
			          console.log(err); 
			        }  
			      });  
			    },
			getIndex(e) {
				console.log(e)
				this.tabIndex = e
			},
			validPay () {
				if (this.tabIndex == 0) {
					if (!(this.formData.orderPhone && this.formData.orderPerson && this.formData.orderAddress)) {
						uni.showToast({
							title: '收货地址未填写',
							icon: "none"
						});
						return false
					}
				} 
				if (this.tabIndex == 1){
					if (!this.formData.orderPickUpTime) {
						uni.showToast({
							title: '自提时间未填写',
							icon: "none"
						});
						return false
					}
					if (!this.formData.orderPhone) {
						uni.showToast({
							title: '联系方式未填写',
							icon: "none"
						});
						return false
					}
				} 
				if (this.tabIndex == 2){
					if (!this.formData.addressPoint) {
						uni.showToast({
							title: '取货点未选择',
							icon: "none"
						});
						return false
					}
					if (!this.formData.orderPhone) {
						uni.showToast({
							title: '联系方式未填写',
							icon: "none"
						});
						return false
					}
				}
				return true
			},
			toPay (orderId, payParams) {
				// 调起微信支付
				return new Promise(resolve => {
					uni.requestPayment({
					  provider: 'wxpay',
					  timeStamp: payParams.timeStamp,
					  nonceStr: payParams.nonceStr,
					  package: payParams.packageValue,
					  signType: payParams.signType,
					  paySign: payParams.paySign,
					  async success(res) {
						uni.showToast({
						  title: '支付成功',
						  icon: 'success',
						});
						await OrderPay({orderId})
						resolve(true)
					  },
					  async fail(err) {
						uni.showToast({
						  title: '支付失败',
						  icon: 'none',
						});
						await OrderCancel({orderId})
						resolve(false)
					  },
					});
				})
			},
			createOrder () {
				if (!this.validPay()) {
					return
				}
				uni.showLoading({
					title: '请稍后'
				});
				let params = Object.assign({}, this.formData) 
				let openid = uni.getStorageSync('config-openid')
				params.customerId = openid
				params.orgCode = shopCode
				params.totalNumber = this.total
				params.orderType = this.tabValue[this.tabIndex]
				params.totalAmount = this.allPrice
				if (this.tabIndex == 0) {
					// 外卖
					params.deliveryFee = this.deliveryFee
				}
				params.items = this.goodsList.map(d => {
					return {
						productId: d.id,
						productName: d.name,
						quantity: d.selected,
						unitPrice: d.price,
						totalPrice: new Big(d.price).times( d.selected)
					}
				})
				if (params.orderPickUpTime) {
					params.orderPickUpTime = params.orderPickUpTime.join(' ')
				}
				CreateOrder(params).then(async res => {
					console.log('CreateOrder', res)
					if (res.code === 20000) {
						uni.hideLoading();
						if (!res.data.prePay) {
							uni.showToast({
								title: '下单失败，支付异常',
								icon: "none"
							});
							return
						}
						let paySuc = await this.toPay(res.data.orderId, res.data.prePay)
						uni.setStorageSync('pay-list', null)
						uni.$emit('refresh-list')
						if (paySuc) {
							uni.showModal({
								title: '提示',
								content: '下单成功',
								showCancel: false,
								success: function (res) {
									if (res.confirm) {
										uni.redirectTo({
											url: `/pages/order/index`
										})
									}
								}
							});
						}
					}else {
						uni.showToast({
							title: res.data,
							icon: "none"
						});
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		padding: 10rpx 20rpx;
		background-color: #f1f2f3;
	}
	.group {
		background-color: #fff;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
	}
	.untoradius {
		border-top-right-radius: 0px;
		border-top-left-radius: 0px;
	}
	.footer-btns {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx;
		border-top: 1rpx solid #eee;
	}
	::v-deep {
		.items {
			flex: 1;
			text-align: center;
			line-height: 80rpx;
			.active {
				background-color: #fff;
				border-top-right-radius: 10rpx;
				border-top-left-radius: 10rpx;
			}
		}
	}
	.inputgb {
		background-color: #f1f2f3;
		padding: 0 20rpx;
		border-radius: 10rpx;
		width: 100%;
		::v-deep {
			.uni-forms-item__label {
				width: 100px;
				font-weight: 500;
				color: #333;
				.label-text {
					color: #333;
				}
			}
			.uni-forms-item__inner {
				position: relative;
				padding-bottom: 0px;
				padding: 20rpx;
			}
			uni-forms-item:not(:last-child), .uni-forms-item:not(:last-child) {
				.uni-forms-item__inner::after{
					position: absolute;
					content: "";
					right: 20rpx;
					left: 20rpx;
					height: 1rpx;
					bottom: 0px;
					background-color: #fff;
				}
			}
		}
	}
</style>